package com.kl.turn;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.LockSupport;

/**
 * 交替输出 park/un-park
 */
@Slf4j
public class AlternateTest3 {
    private final int loopNum;

    public AlternateTest3(int loopNum) {
        this.loopNum = loopNum;
    }

    public void print(String str, Thread next) {
        for (int i = 0; i < loopNum; i++) {
            LockSupport.park();        //三个线程一进入方法都先阻塞
            log.info(str);
            LockSupport.unpark(next);  //给next线程一张通行证
        }
    }

    //声明三个线程
    static Thread t1;
    static Thread t2;
    static Thread t3;

    public static void main(String[] args) throws InterruptedException {
        AlternateTest3 alternateTest3 = new AlternateTest3(5);
        t1 = new Thread(() -> {
            alternateTest3.print("A", t2);
        }, "线程t1");

        t2 = new Thread(() -> {
            alternateTest3.print("B", t3);
        }, "线程t2");

        t3 = new Thread(() -> {
            alternateTest3.print("C", t1);
        }, "线程t3");

        t1.start();
        t2.start();
        t3.start();
        Thread.sleep(1000);
        LockSupport.unpark(t1);    //由主函数作为媒介唤醒线程t1后进入打印循环
    }
}